package org.bpms.util;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.lang.reflect.InvocationTargetException;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.List;
import java.util.Random;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.apache.commons.beanutils.BeanUtils;
import org.apache.tools.zip.ZipEntry;
import org.apache.tools.zip.ZipFile;
import org.bpms.model.admin.Book;
import org.bpms.model.admin.Booktemp;

import com.github.junrar.Archive;
import com.github.junrar.rarfile.FileHeader;

/**
 * 压缩解压缩工具包
 * @author hupei
 *
 */
public class Compress {
	
	/**
	 * 解压zip文件
	 * @param zipfile
	 * @param descDir
	 */
    public static String unZipFiles(List<String> files , java.io.File zipfile) {
    	String path = zipfile.getAbsolutePath();
    	path = path.substring(0, path.lastIndexOf("."))+"/";
        File dstDiretory = new File(path);
        if (!dstDiretory.exists()) {// 目标目录不存在时，创建该文件夹
            dstDiretory.mkdirs();
        }
        try {
            ZipFile zf = new ZipFile(zipfile , "GBK");
            for (Enumeration entries = zf.getEntries(); entries
                    .hasMoreElements();) {
                ZipEntry entry = ((ZipEntry) entries.nextElement());
                String zipEntryName =  entry.getName();
                String fileExt = zipEntryName.substring(zipEntryName.lastIndexOf(".") + 1);
                if (!zipEntryName.contains(".")){
                	File uploadDir = new File(path + zipEntryName);
                	if (!uploadDir.exists()){
                		uploadDir.mkdirs();
                	}
                }else if(fileExt.equals("xls")){
                    InputStream in = zf.getInputStream(entry);
                    FileOutputStream out = new FileOutputStream(path + zipEntryName);
                    byte[] buf1 = new byte[1024];
                    int len;
                    while ((len = in.read(buf1)) > 0) {
                        out.write(buf1, 0, len);
                    }
                    in.close();
                    out.close(); 
                    files.add(path + zipEntryName);
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return path;
    }
    
    /**
     * 解压rar文件 返回文件夹路径
     * @param srcRarPath
     * @param dstDirectoryPath
     */
    public static String unRarFile(List<String> files ,java.io.File rarfile) {
    	String dstDirectoryPath = rarfile.getAbsolutePath();
    	dstDirectoryPath = dstDirectoryPath.substring(0, dstDirectoryPath.lastIndexOf("."))+"/";
        File dstDiretory = new File(dstDirectoryPath);
        if (!dstDiretory.exists()) {// 目标目录不存在时，创建该文件夹
            dstDiretory.mkdirs();
        }
        Archive a = null;
        try {
            a = new Archive(rarfile);
            if (a != null) {
                //a.getMainHeader().print(); // 打印文件信息.
                FileHeader fh = a.nextFileHeader();
                while (fh != null) {
                	String fileName=fh.getFileNameW().trim();
                	if(!existZH(fileName)){  
                        fileName = fh.getFileNameString().trim();  
                    } 
                	String fileExt = fileName.substring(fileName.lastIndexOf(".") + 1);
                    if (fh.isDirectory()) { // 文件夹 
                        File fol = new File(dstDirectoryPath + File.separator
                                + fileName);
                        fol.mkdirs();
                    } else if(fileExt.equals("xls")){ // 文件
                        File out = new File(dstDirectoryPath + File.separator
                                + fileName);
                        files.add(out.getAbsolutePath());
                        //System.out.println(out.getAbsolutePath());
                        try {// 之所以这么写try，是因为万一这里面有了异常，不影响继续解压. 
                            if (!out.exists()) {
                                if (!out.getParentFile().exists()) {// 相对路径可能多级，可能需要创建父目录. 
                                    out.getParentFile().mkdirs();
                                }
                                out.createNewFile();
                            }
                            FileOutputStream os = new FileOutputStream(out);
                            a.extractFile(fh, os);
                            os.close();
                        } catch (Exception ex) {
                            ex.printStackTrace();
                        }
                    }
                    fh = a.nextFileHeader();
                }
                a.close();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return dstDirectoryPath;
    }
    
    /**
     * 判断文件名有无中文
     * @param str
     * @return
     */
    public static boolean existZH(String str) {  
        String regEx = "[\\u4e00-\\u9fa5]";  
        Pattern p = Pattern.compile(regEx);  
        Matcher m = p.matcher(str);  
        while (m.find()) {  
            return true;  
        }  
        return false;  
    }   
    public static void main(String [] args) throws IllegalAccessException, InvocationTargetException{
    	Book b = new Book();
    	b.set("name", "hupei");
    	Booktemp temp = new Booktemp();
    	BeanUtils.copyProperties(b , temp);
    	System.out.println(temp.getStr("name"));
    }
}
